package com.ydl.partitionscheduler.strategy;

import com.ydl.partitionscheduler.config.TablePartitionProperties;
import com.ydl.partitionscheduler.model.PartitionInfo;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Component
public class MonthlyPartitionStrategy implements PartitionStrategy {

    @Override
    public String getStrategyName() {
        return "monthly";
    }

    @Override
    public List<PartitionInfo> generatePartitions(TablePartitionProperties.TablePartitionConfig config) {
        List<PartitionInfo> partitions = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(config.getValuePattern());
        LocalDate currentDate = LocalDate.now();

        for (int i = 0; i < config.getPreCreateCount(); i++) {
            LocalDate partitionDate = currentDate.plusMonths(i).withDayOfMonth(1);
            LocalDate nextMonth = partitionDate.plusMonths(1).withDayOfMonth(1);
            PartitionInfo partition = new PartitionInfo();
            partition.setPartitionName(config.getNamePattern()
                    .replace("${mainTable}", config.getMainTable())
                    .replace("${partitionSuffix}", partitionDate.format(DateTimeFormatter.ofPattern("yyyyMM"))));
            partition.setStartValue(partitionDate.format(formatter));
            partition.setEndValue(nextMonth.format(formatter));
            partitions.add(partition);
        }

        return partitions;
    }
}
